import type { ProFormInstance } from '@ant-design/pro-form';
import { ProFormSelect, StepsForm } from '@ant-design/pro-form';
import { Button, Form, Input, message, Modal, TreeSelect } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import type { AddAdminBean } from '../data';
import { queryPositionByDep, querySuperiorMent, registerAdmin } from '../service';
import { queryDepartment } from '../../Department/service';

interface AddFormProps {
  reloadFunc: any;
  onCancel: (flag?: boolean) => void;
  modalVisible: boolean;
}
const AddForm: React.FC<AddFormProps> = (props) => {
  const form = useRef<ProFormInstance>();

  const [treeDate, setTreeDate] = useState<any[]>([]);
  const [positionData, setPositionData] = useState<any[]>();
  const [owningAccount, setOwningAccount] = useState<any[]>();
  const [oneTreeDisplay, setOneTreeDisplay] = useState(false);
  const [twoTreeDisplay, setTwoTreeDisplay] = useState(true);
  const [selectDisplay, setSelectDisplay] = useState(true);
  const [formLoading, setFormLoading] = useState([true, false, false]);

  function convertData(data: { id: any; name: any; next_level: string | any[] }) {
    const node = {
      value: data.id,
      title: data.name,
      children: [] as any,
    };
    if (data.next_level && data.next_level.length > 0) {
      for (let i = 0; i < data.next_level.length; i++) {
        const child = convertData(data.next_level[i]);
        node.children.push(child);
      }
    }
    return node;
  }

  useEffect(() => {

    queryDepartment().then((res) => {
      if (res && res.code == 0) {
        const data = res?.data;
        const convert = [];
        if (data && data.length > 0) {
          for (let i = 0; i < data.length; i++) {
            convert.push(convertData(data[i]));
          }
          setTreeDate(convert);
        }
      }
      setFormLoading([false, false, false]);
    });
  }, []);
  const { reloadFunc, onCancel: handleAddModalVisible, modalVisible: addModalVisible } = props;

  return (
    <Modal
      title="新建账号"
      open={addModalVisible}
      destroyOnClose
      width={650}
      style={{ marginTop: 150 }}
      onCancel={() => handleAddModalVisible(false)}
      afterClose={() => handleAddModalVisible()}
      okText="确定"
      footer={null}
      cancelText="取消"
    >
      <StepsForm<AddAdminBean>
        formRef={form}
        onFinish={async (values) => {
          const value = {
            ...values,
            belong: String(values.belong),
          };
          const hide = message.loading('正在添加');
          const res = await registerAdmin(value);
          hide();
          if (res && res.code === 0) {
            message.success(res.message);
            handleAddModalVisible(false);
            reloadFunc();
            return true;
          } else {
            message.error(res.message || '添加失败');
            return false;
          }
        }}
        submitter={{
          render: (props) => {
            if (props.step === 0) {
              return (
                <>
                  <Button
                    type="primary"
                    onClick={() => {
                      setOneTreeDisplay(false);
                      setTwoTreeDisplay(true);
                      setSelectDisplay(true);
                      props.form?.resetFields();
                    }}
                  >
                    重置
                  </Button>
                  <Button type="primary" onClick={() => props.onSubmit?.()}>
                    下一步
                  </Button>
                </>
              );
            }
            if (props.step === 1) {
              return [
                <Button key="pre" onClick={() => props.onPre?.()}>
                  上一步
                </Button>,
                <Button type="primary" key="goToTree" onClick={() => props.onSubmit?.()}>
                  提交
                </Button>,
              ];
            }
          },
        }}
      >
        <StepsForm.StepForm
          layout="horizontal"
          title="职位选择"
          style={{ width: 550 }}
        >
          <Form.Item
            name="department_id"
            label="部门选择"
            rules={[{ required: true, message: '必填' }]}
          >
            <TreeSelect
              loading={formLoading[0]}
              disabled={oneTreeDisplay}
              showSearch
              style={{ width: '100%' }}
              dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
              placeholder="请选择部门"
              allowClear
              autoClearSearchValue
              treeDefaultExpandAll
              onChange={(newValue, _labelList) => {
                if (newValue) {
                  setFormLoading([false, true, false]);
                  queryPositionByDep(newValue).then((res) => {
                    if (res && res.code == 0 && res.data.length > 0) {
                      const data = res?.data;
                      const convert = [];
                      for (let i = 0; i < data.length; i++) {
                        convert.push(convertData(data[i]));
                      }
                      setPositionData(convert);
                      setOneTreeDisplay(true);
                      setTwoTreeDisplay(false);
                      setFormLoading([false, false, false]);
                    } else {
                      message.error("暂无可选职位")
                      setFormLoading([false, false, false]);
                    }
                  });
                }
              }}
              treeData={treeDate}
            />
          </Form.Item>
          <Form.Item
            name="position_id"
            label="职位选择"
            rules={[{ required: true, message: '必填' }]}
          >
            <TreeSelect
              loading={formLoading[1]}
              disabled={twoTreeDisplay}
              autoClearSearchValue
              showSearch
              onChange={(newValue) => {
                setFormLoading([false, false, true]);
                querySuperiorMent(newValue).then((res) => {
                  if (res && res.code == 0 && res.data.length > 0) {
                    setOwningAccount(
                      res.data?.map((item: { id: any; name: any }) => {
                        return {
                          value: item.id,
                          label: item.name,
                        };
                      }),
                    );
                    setTwoTreeDisplay(true);
                    setSelectDisplay(false);
                    setFormLoading([false, false, false]);
                  } else {
                    setFormLoading([false, false, false]);
                    message.error('无上级，请先创建上级');
                  }
                });
              }}
              style={{ width: '100%' }}
              dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
              placeholder="请选择职位"
              allowClear
              treeDefaultExpandAll
              treeData={positionData}
            />
          </Form.Item>
          <ProFormSelect
            fieldProps={{
              loading: formLoading[2],
            }}
            options={owningAccount}
            label={'所属上级'}
            disabled={selectDisplay}
            name="belong"
            rules={[{ required: true, message: '请选择所属企业' }]}
            placeholder="选择所属上级（请先选择职位）"
          />
        </StepsForm.StepForm>

        <StepsForm.StepForm layout="horizontal" title="信息配置" style={{ width: 550 }}>
          <Form.Item name="name" label="用户名称" rules={[{ required: true, message: '必填' }]}>
            <Input />
          </Form.Item>
          <Form.Item name="account" label="用户账户" rules={[{ required: true, message: '必填' }]}>
            <Input />
          </Form.Item>
          <Form.Item name="password" label="用户密码" rules={[{ required: true, message: '必填' }]}>
            <Input type="password" />
          </Form.Item>
          <Form.Item name="mobile" label="手机号码" rules={[{ required: true, message: '必填' }]}>
            <Input />
          </Form.Item>
        </StepsForm.StepForm>
      </StepsForm>
    </Modal>
  );
};

export default AddForm;
